import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_localizations/flutter_localizations.dart';

void main(List<String> args) {
  runApp(MaterialApp(
    home: LocaleTest(),
  ));
}

class LocaleTest extends StatefulWidget {
  const LocaleTest({super.key});

  @override
  State<LocaleTest> createState() => _LocaleTestState();
}

class _LocaleTestState extends State<LocaleTest> {
  Locale _locale = Locale('zh', 'CN'); // 初始Locale

  void _changeLocale(Locale locale) {
    setState(() {
      _locale = locale;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      localizationsDelegates: [
        GlobalMaterialLocalizations.delegate, // 以MaterialApp为入口的应用
        // GlobalWidgetsLocalizations.delegate, // 以WidgetApp为入口的应用
        // 注册我们的Delegate
        DemoLocalizationsDelegate()
      ],
      locale: _locale,
      supportedLocales: [
        const Locale('en', 'US'), // 美国英语
        const Locale('zh', 'CN'), // 中文简体
        //其他Locales
      ],
      home: HomeDemo(_changeLocale),
    );
  }
}

class HomeDemo extends StatelessWidget {
  HomeDemo(this.changeLocale);

  final ValueChanged<Locale> changeLocale;

  @override
  Widget build(BuildContext context) {
    final DemoLocalizations? localizations =
        Localizations.of(context, DemoLocalizations);

    return Scaffold(
      appBar: AppBar(
        title: Text(localizations!.translate('app_title')),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(localizations.translate('hello').replaceFirst("%s", "sbjun")),
            SizedBox(height: 30),
            Text("通过自定义LocalizationsDelegate，实现多语言切换，写的代码并不少呀"),
          ],
        ),
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.miniEndTop,
      floatingActionButton: ElevatedButton.icon(
        icon: Icon(Icons.switch_access_shortcut),
        onPressed: () {
          Locale locale = Localizations.localeOf(context);
          if (locale.languageCode == 'zh') {
            changeLocale(const Locale('en', 'US'));
          } else {
            changeLocale(const Locale('zh', 'CN'));
          }
        },
        label: Text(localizations.translate('button_label')), // 你可以更换为你需要的图标
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

//Locale资源类
class DemoLocalizations {
  late Map<String, String> _localizedStrings;

  // DemoLocalizations(this._localizedStrings);
  DemoLocalizations(Map<String, dynamic> jsonMap) {
    _localizedStrings =
        jsonMap.map((key, value) => MapEntry(key, value.toString()));
  }

  // 获取本地化字符串的方法
  String translate(String key) {
    return _localizedStrings[key] ?? '*** $key not found ***';
  }
}

//Locale代理类
class DemoLocalizationsDelegate
    extends LocalizationsDelegate<DemoLocalizations> {
  const DemoLocalizationsDelegate();

  //是否支持某个Local
  @override
  bool isSupported(Locale locale) => ['en', 'zh'].contains(locale.languageCode);

  // Flutter会调用此类加载相应的Locale资源类
  @override
  Future<DemoLocalizations> load(Locale locale) {
    // 异步加载本地化资源: assets/jsons
    final String fileName = './jsons/${locale.languageCode}.json';
    return rootBundle.loadString(fileName).then((string) {
      final Map<String, dynamic> jsonMap = json.decode(string);
      return DemoLocalizations(jsonMap);
    });
  }

  @override
  // 始终返回 true，以便在语言更改时重新加载资源
  bool shouldReload(DemoLocalizationsDelegate old) => true;
}
